package com.cj.tool

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import androidx.core.view.isVisible
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.cj.publish.utils.execute
import com.cj.publish.utils.gotoAct
import com.cj.publish.utils.toast
import com.cj.tool.bean.LocationBean
import com.cj.tool.http.BaseObserver
import com.cj.tool.http.RestClient
import com.cj.tool.utils.LogUtil
import com.cj.tool.utils.SimpleConfig
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.layout_input.*
import kotlinx.android.synthetic.main.layout_input.view.*
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import java.text.DecimalFormat


class MainActivity : BaseActivity() {

    private lateinit var locationClient: LocationClient
    private var dialog: BottomSheetDialog? = null

    override fun layoutId(): Int {
        return R.layout.activity_main
    }

    override fun initView() {
        getPageHead(this, null).apply {
            setTitleText("经纬度定位工具")
        }
        initMap()
    }
    

    private fun initMap() {
        //是否双击放大当前地图中心点 默认：false 即按照双击位置放大地图
        mapView.map.uiSettings.setEnlargeCenterWithDoubleClickEnable(true)
        //去除缩放工具
        mapView.showZoomControls(false)
        //去除百度logo
        mapView.removeViewAt(1)
        //开启地图的定位图层
        mapView.map.isMyLocationEnabled = true
        //定位初始化
        locationClient = LocationClient(this)
        //通过LocationClientOption设置LocationClient相关参数
        val option = LocationClientOption()
        // 打开gps
        option.isOpenGps = true
        // 设置坐标类型
        option.setCoorType("bd09ll")
        option.setScanSpan(1000)
        //设置locationClientOption
        locationClient.locOption = option

        //注册LocationListener监听器
        locationClient.registerLocationListener(object : BDAbstractLocationListener() {
            override fun onReceiveLocation(location: BDLocation?) {
                location?.apply {
                    mapView?.apply {
                        val locData = MyLocationData.Builder()
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                            .accuracy(location.radius)
                            //.direction(location.direction)
                            .latitude(location.latitude)
                            .longitude(location.longitude).build()
                        map.setMyLocationData(locData)
                        resetMap(LatLng(location.latitude, location.longitude))
                        locationClient.stop()
                    }
                }
            }
        })
        //开启地图定位图层
        locationClient.start()
    }

    override fun setListener() {
        btn_history.setOnClickListener {
            gotoAct<IconActivity>()
        }
        btn_submit.setOnClickListener {
            if (dialog == null) {
                dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
            }
            val view = LayoutInflater.from(this).inflate(R.layout.layout_input, null)
            view?.apply {
                var currentSelect = ""
                val user =
                    SimpleConfig.getParam(
                        this@MainActivity,
                        LoginActivity.INPUT_USER,
                        "admin"
                    ) as String
                tv_input_lat.text = tv_lat.text.toString()
                tv_input_lng.text = tv_lng.text.toString()
                et_input_type.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                    override fun onNothingSelected(parent: AdapterView<*>?) {
                    }

                    override fun onItemSelected(
                        parent: AdapterView<*>?,
                        view: View?,
                        position: Int,
                        id: Long
                    ) {
                        currentSelect = parent?.selectedItem.toString()
                        LogUtil.e(currentSelect)
                    }
                }
                btn_copy.setOnClickListener {
                    //第一个参数，是描述复制的内容，也可以和内容一样。
                    val clipData = ClipData.newPlainText(
                        "经纬度",
                        "经纬度：${tv_lat.text},${tv_lng.text}"
                    )
                    val mClipboardManager: ClipboardManager =
                        getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    mClipboardManager.setPrimaryClip(clipData)
                    toast("复制成功")

                }
                btn_input_submit.setOnClickListener {
                    if (et_input_title.text.toString().isNullOrEmpty()) {
                        toast("标题栏不能为空")
                        return@setOnClickListener
                    }
                    val bean = LocationBean(
                        tv_lat.text.toString(), tv_lng.text.toString(),
                        et_input_title.text.toString().trim(), currentSelect, user
                    )
                    val body: RequestBody = RequestBody.create(
                        MediaType.parse("application/json; charset=utf-8"),
                        Gson().toJson(bean)
                    )
                    execute(RestClient().httpService.uploadLocation(body),
                        object : BaseObserver<ResponseBody>(this@MainActivity, true) {
                            override fun onNext(t: ResponseBody) {
                                val jsonObject = JSONObject(t.string())
                                jsonObject.optString("code").apply {
                                    if ("200" == this) {
                                        toast("位置上传成功")
                                        dialog?.dismiss()
                                    } else {
                                        toast(jsonObject.optString("msg"))
                                    }
                                }
                            }

                        })
                }
            }
            dialog?.setContentView(view)
            dialog?.show()
        }
        mapView.map.setOnMapStatusChangeListener(object : BaiduMap.OnMapStatusChangeListener {
            override fun onMapStatusChangeStart(p0: MapStatus?) {
                mapView.map.clear()
                iv_map.isVisible = true
            }

            override fun onMapStatusChangeStart(p0: MapStatus?, p1: Int) {
            }

            override fun onMapStatusChange(p0: MapStatus?) {

            }

            override fun onMapStatusChangeFinish(p0: MapStatus?) {
                p0?.apply {
                    mapView.map.clear()
                    iv_map.visibility = View.INVISIBLE
                    setMarker(p0.target)
                }

            }

        })

    }

    override fun onResume() {
        super.onResume()
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理  
        mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理  
        mapView.onPause()
    }

    override fun onDestroy() {
        locationClient.stop()
        mapView.map.isMyLocationEnabled = false;
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理  
        mapView.onDestroy()
        super.onDestroy()

    }

    private fun resetMap(latLng: LatLng) {
        val builder = MapStatus.Builder()
        builder.target(latLng).zoom(18f)
        mapView.map.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()))
        setMarker(latLng)
    }

    //构建Marker图标
    private fun setMarker(latLng: LatLng) {
        ll_point.isVisible = true
        tv_lat?.text = DecimalFormat("#.000000").format(latLng.latitude)
        tv_lng?.text = DecimalFormat("#.000000").format(latLng.longitude)
        //构建MarkerOption，用于在地图上添加Marker
        val option: OverlayOptions = MarkerOptions()
            .position(latLng)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map))
        //在地图上添加Marker，并显示
        mapView.map.addOverlay(option)
    }
}